<template>
  <div class="hotel-detail bg-gray-50 dark:bg-gray-900 min-h-screen">
    <!-- 面包屑导航 -->
    <div class="container mx-auto px-4 py-4">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/hotel' }"
          >酒店预订</el-breadcrumb-item
        >
        <el-breadcrumb-item>{{ hotel.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 页面加载状态 -->
    <el-skeleton :loading="loading" animated class="w-full">
      <template #template>
        <div class="container mx-auto px-4">
          <el-skeleton-item variant="p" style="width: 50%; height: 30px;" class="mb-4" />
          <div class="flex gap-8">
            <div class="w-[500px]">
              <el-skeleton-item variant="image" style="width: 100%; height: 300px;" />
            </div>
            <div class="flex-1">
              <el-skeleton-item variant="h1" style="width: 50%; height: 30px;" class="mb-4" />
              <el-skeleton-item variant="text" style="width: 30%; height: 20px;" class="mb-3" />
              <el-skeleton-item variant="text" style="width: 100%; height: 20px;" class="mb-3" />
              <el-skeleton-item variant="text" style="width: 100%; height: 20px;" class="mb-3" />
            </div>
          </div>
        </div>
      </template>

      <template #default>
    <!-- 酒店基本信息 -->
    <div class="hotel-info bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4">
        <div class="py-8">
          <div class="flex gap-8">
            <!-- 酒店图片轮播 -->
            <div class="w-[500px]">
              <el-carousel :interval="4000" type="card" height="300px">
                <el-carousel-item v-for="image in hotel.images" :key="image">
                  <el-image :src="image" fit="cover" class="w-full h-full" />
                </el-carousel-item>
              </el-carousel>
            </div>

            <!-- 酒店信息 -->
            <div class="flex-1">
              <div class="flex justify-between items-start">
                <div>
                  <h1
                    class="text-2xl font-bold text-gray-900 dark:text-white mb-4"
                  >
                    {{ hotel.name }}
                  </h1>
                  <div class="flex items-center gap-2 mb-4">
                    <el-rate v-model="hotel.rating" disabled allow-half />
                    <span class="text-orange-500">{{ hotel.rating }}分</span>
                    <span class="text-gray-500"
                      >({{ hotel.reviewCount }}条点评)</span
                    >
                  </div>
                  <p class="text-gray-600 dark:text-gray-400 mb-4">
                    {{ hotel.address }}
                  </p>
                  <div class="flex flex-wrap gap-2 mb-4">
                    <el-tag
                      v-for="tag in hotel.tags"
                      :key="tag"
                      size="small"
                      class="mr-1"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
                <div>
                  <el-button
                    :type="hotel.isFavorite ? 'danger' : 'default'"
                    :icon="Star"
                    @click="toggleFavorite"
                  >
                    {{ hotel.isFavorite ? "已收藏" : "收藏" }}
                  </el-button>
                </div>
              </div>

              <!-- 设施服务 -->
              <div class="facilities mt-6">
                <h3 class="text-lg font-medium mb-4">设施服务</h3>
                <div class="grid grid-cols-3 gap-4">
                  <div
                    v-for="facility in hotel.facilities"
                    :key="facility.name"
                    class="flex items-center gap-2"
                  >
                    <el-icon><component :is="facility.icon" /></el-icon>
                    <span>{{ facility.name }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex gap-8">
        <!-- 左侧内容 -->
        <div class="flex-1">
          <!-- 房型列表 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-8">
            <h2 class="text-xl font-bold mb-6">选择房型</h2>

            <!-- 日期选择 -->
            <div class="date-picker mb-6">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="入住日期"
                end-placeholder="离店日期"
                :size="'default'"
                class="w-[300px]"
                @change="handleDateChange"
              />
            </div>

            <!-- 房型卡片 -->
            <div class="space-y-6">
              <div
                v-for="room in hotel.rooms"
                :key="room.id"
                class="room-card border border-gray-200 dark:border-gray-700 rounded-lg p-4"
              >
                <div class="flex gap-6">
                  <!-- 房型图片 -->
                  <div class="w-48">
                    <el-image
                      :src="room.image"
                      fit="cover"
                      class="w-full h-32 rounded-lg"
                    />
                  </div>

                  <!-- 房型信息 -->
                  <div class="flex-1">
                    <div class="flex justify-between items-start">
                      <div>
                        <h3 class="text-lg font-medium mb-2">
                          {{ room.name }}
                        </h3>
                        <p
                          class="text-gray-600 dark:text-gray-400 text-sm mb-2"
                        >
                          {{ room.description }}
                        </p>
                        <div class="flex flex-wrap gap-2">
                          <el-tag
                            v-for="feature in room.features"
                            :key="feature"
                            size="small"
                            class="mr-1"
                          >
                            {{ feature }}
                          </el-tag>
                        </div>
                      </div>
                      <div class="text-right">
                        <div class="text-2xl font-bold text-primary-600 mb-2">
                          ¥{{ room.price }}
                          <span class="text-sm text-gray-500">/晚</span>
                        </div>
                        <div class="text-sm text-gray-500 mb-2">
                          剩余 {{ room.available }} 间
                        </div>
                        <el-button
                          type="primary"
                          :disabled="!room.available"
                          @click="handleBookRoom(room)"
                        >
                          立即预订
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 酒店介绍 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-8">
            <el-tabs v-model="activeTab">
              <el-tab-pane label="酒店介绍" name="intro">
                <div class="rich-text" v-html="hotel.introduction"></div>
              </el-tab-pane>
              <el-tab-pane label="周边设施" name="surroundings">
                <div class="surroundings-content">
                  <!-- 周边设施内容 -->
                  <div v-if="hotel.surroundings && hotel.surroundings.length > 0">
                    <div v-for="(item, index) in hotel.surroundings" :key="index" class="mb-6">
                      <h3 class="text-lg font-medium mb-3">{{ item.category }}</h3>
                      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div v-for="facility in item.facilities" :key="facility.name" class="flex items-start gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                          <el-icon class="text-primary-500"><Location /></el-icon>
                          <div>
                            <div class="font-medium">{{ facility.name }}</div>
                            <div class="text-sm text-gray-500 dark:text-gray-400">{{ facility.distance }}</div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="用户点评" name="reviews">
                <div class="reviews-content">
                  <!-- 用户点评内容 -->
                  <div v-if="hotel.reviews && hotel.reviews.length > 0">
                    <div class="review-summary flex items-center gap-6 mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                      <div class="rating-overview text-center">
                        <div class="text-3xl font-bold text-primary-600">{{ hotel.rating }}</div>
                        <div class="text-sm text-gray-500 dark:text-gray-400">综合评分</div>
                        <el-rate v-model="hotel.rating" disabled allow-half class="mt-2" />
                      </div>
                      <div class="flex-1">
                        <div class="text-sm text-gray-600 dark:text-gray-300 mb-2">评分分布</div>
                        <div class="grid grid-cols-2 gap-x-4 gap-y-2">
                          <div class="flex items-center gap-2" v-for="(score, index) in ratingDistribution" :key="index">
                            <span class="text-gray-600 dark:text-gray-300 w-16">{{ score.label }}</span>
                            <el-progress :percentage="score.percentage" :stroke-width="10" :show-text="false" :color="score.color" class="flex-1" />
                            <span class="text-gray-500 dark:text-gray-400 w-8 text-right">{{ score.percentage }}%</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <div class="review-list space-y-5">
                      <div v-for="review in hotel.reviews" :key="review.id" class="review-item p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                        <div class="review-header flex justify-between items-start mb-3">
                          <div class="flex items-center gap-3">
                            <el-avatar :size="40" :src="review.avatar">{{ review.username.substring(0, 1) }}</el-avatar>
                            <div>
                              <div class="font-medium">{{ review.username }}</div>
                              <div class="text-sm text-gray-500 dark:text-gray-400">{{ review.date }}</div>
                            </div>
                          </div>
                          <div class="flex items-center">
                            <el-rate v-model="review.rating" disabled allow-half />
                            <span class="ml-2 text-orange-500">{{ review.rating }}分</span>
                          </div>
                        </div>
                        <div class="review-content text-gray-600 dark:text-gray-300">
                          {{ review.content }}
                        </div>
                        <div v-if="review.reply" class="review-reply mt-3 p-3 bg-gray-50 dark:bg-gray-700 rounded">
                          <div class="text-sm font-medium mb-1">酒店回复：</div>
                          <div class="text-sm text-gray-600 dark:text-gray-400">{{ review.reply }}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>

        <!-- 右侧地图 -->
        <div class="w-[300px]">
          <div
            class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 sticky top-4"
          >
            <h3 class="text-lg font-medium mb-4">位置与交通</h3>
            <div ref="mapContainer" class="map-container h-[200px] mb-4 rounded-lg">
              <!-- 地图将在这里显示 -->
            </div>
            <div class="text-sm text-gray-600 dark:text-gray-400">
              <p class="mb-2">{{ hotel.address }}</p>
              <p v-if="hotel.subway" class="mb-2">地铁: {{ hotel.subway }}</p>
              <p v-if="hotel.landmarks" class="mb-2">
                地标: {{ hotel.landmarks }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
      </template>
    </el-skeleton>

    <!-- 预订弹窗 -->
    <el-dialog
      v-model="showBookingDialog"
      title="预订确认"
      width="600px"
      class="booking-dialog"
      :close-on-click-modal="false"
    >
      <!-- 弹窗内容区域 -->
      <div class="dialog-content">
        <!-- 房型信息预览 固定在顶部 -->
        <div
          class="room-preview sticky top-0 z-10 bg-white dark:bg-gray-800 mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
        >
          <div class="flex gap-4">
            <el-image
              :src="selectedRoom?.image"
              fit="cover"
              class="w-24 h-24 rounded-lg"
            />
            <div class="flex-1">
              <h3 class="text-lg font-medium mb-2">{{ selectedRoom?.name }}</h3>
              <p class="text-sm text-gray-600 dark:text-gray-400 mb-2">
                {{ selectedRoom?.description }}
              </p>
              <div class="text-primary-600 font-bold">
                ¥{{ selectedRoom?.price
                }}<span class="text-sm text-gray-500">/晚</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 可滚动的表单内容区域 -->
        <div class="form-content">
          <el-form
            ref="bookingFormRef"
            :model="bookingForm"
            :rules="bookingRules"
            label-width="100px"
          >
            <!-- 入住信息 -->
            <div class="form-section mb-6">
              <h4 class="text-lg font-medium mb-4">入住信息</h4>
              <el-form-item label="入住日期">
                <div class="flex items-center text-gray-600 dark:text-gray-400">
                  <span>{{ formatDate(dateRange[0]) }}</span>
                  <el-icon class="mx-2"><ArrowRight /></el-icon>
                  <span>{{ formatDate(dateRange[1]) }}</span>
                  <span class="ml-2 text-sm"
                    >(共{{ calculateNights() }}晚)</span
                  >
                </div>
              </el-form-item>
              <el-form-item label="房间数量" prop="roomCount">
                <el-input-number
                  v-model="bookingForm.roomCount"
                  :min="1"
                  :max="selectedRoom?.available || 1"
                  @change="handleRoomCountChange"
                />
              </el-form-item>
              <el-form-item label="入住人数" prop="guestCount">
                <el-input-number
                  v-model="bookingForm.guestCount"
                  :min="1"
                  :max="bookingForm.roomCount * 2"
                />
                <span class="text-sm text-gray-500 ml-2">每间最多2人</span>
              </el-form-item>
            </div>

            <!-- 入住人信息 -->
            <div class="form-section mb-6">
              <h4 class="text-lg font-medium mb-4">入住人信息</h4>
              <el-form-item
                v-for="(guest, index) in bookingForm.guests"
                :key="index"
                :label="'入住人' + (index + 1)"
                :prop="'guests.' + index + '.name'"
                :rules="[
                  {
                    required: true,
                    message: '请输入入住人姓名',
                    trigger: 'blur',
                  },
                  {
                    min: 2,
                    max: 20,
                    message: '长度在 2 到 20 个字符',
                    trigger: 'blur',
                  },
                ]"
              >
                <div class="flex gap-4">
                  <el-input v-model="guest.name" placeholder="请输入姓名" />
                  <el-select v-model="guest.idType" placeholder="证件类型">
                    <el-option label="身份证" value="idcard" />
                    <el-option label="护照" value="passport" />
                  </el-select>
                  <el-input
                    v-model="guest.idNumber"
                    placeholder="请输入证件号码"
                  />
                </div>
              </el-form-item>
            </div>

            <!-- 联系人信息 -->
            <div class="form-section mb-6">
              <h4 class="text-lg font-medium mb-4">联系人信息</h4>
              <el-form-item label="联系人" prop="contactName">
                <el-input
                  v-model="bookingForm.contactName"
                  placeholder="请输入联系人姓名"
                />
              </el-form-item>
              <el-form-item label="手机号码" prop="contactPhone">
                <el-input
                  v-model="bookingForm.contactPhone"
                  placeholder="请输入手机号码"
                />
              </el-form-item>
              <el-form-item label="电子邮箱" prop="contactEmail">
                <el-input
                  v-model="bookingForm.contactEmail"
                  placeholder="用于接收订单确认邮件"
                />
              </el-form-item>
            </div>

            <!-- 其他需求 -->
            <div class="form-section mb-6">
              <h4 class="text-lg font-medium mb-4">其他需求</h4>
              <el-form-item label="预计到店" prop="arrivalTime">
                <el-time-select
                  v-model="bookingForm.arrivalTime"
                  start="00:00"
                  step="00:30"
                  end="23:30"
                  placeholder="请选择预计到店时间"
                />
                <div class="text-sm text-gray-500 mt-1">
                  酒店办理入住时间为14:00后，如需提前到店请联系酒店
                </div>
              </el-form-item>
              <el-form-item label="特殊要求">
                <el-input
                  v-model="bookingForm.remarks"
                  type="textarea"
                  rows="3"
                  placeholder="如有特殊要求请在此说明（如无烟房、高层房等），酒店会尽量安排"
                />
              </el-form-item>
            </div>
          </el-form>

          <!-- 费用明细 -->
          <div
            class="fee-details mt-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
          >
            <h4 class="text-lg font-medium mb-4">费用明细</h4>
            <div class="space-y-2">
              <div class="flex justify-between items-center">
                <div>
                  <span>房费</span>
                  <span class="text-sm text-gray-500 ml-2">
                    ({{ bookingForm.roomCount }}间 × {{ calculateNights() }}晚 ×
                    ¥{{ selectedRoom?.price }})
                  </span>
                </div>
                <span>¥{{ calculateRoomFee() }}</span>
              </div>
              <div class="flex justify-between">
                <div>
                  <span>服务费</span>
                  <el-tooltip
                    content="包含预订服务费、平台服务费等"
                    placement="top"
                  >
                    <el-icon class="ml-1"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
                <span>¥{{ calculateServiceFee() }}</span>
              </div>
              <div
                class="border-t border-gray-200 dark:border-gray-600 my-2"
              ></div>
              <div class="flex justify-between text-lg font-bold">
                <span>总计</span>
                <span class="text-primary-600">¥{{ calculateTotalFee() }}</span>
              </div>
            </div>
          </div>

          <!-- 预订须知 -->
          <div class="booking-notice mt-6 text-sm text-gray-500">
            <h4
              class="text-base font-medium text-gray-900 dark:text-white mb-2"
            >
              预订须知
            </h4>
            <ul class="list-disc list-inside space-y-1">
              <li>请确保填写的入住人信息准确，入住时需出示相关证件</li>
              <li>订单确认后将发送确认短信和邮件到您的手机和邮箱</li>
              <li>如需发票，请在入住时向酒店前台索取</li>
              <li>入住前24小时内取消预订将收取首晚房费</li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 底部操作区域 固定在底部 -->
      <template #footer>
        <div class="dialog-footer flex items-center justify-between">
          <div class="text-sm text-gray-500">
            点击确认即表示您同意
            <el-link type="primary" @click="showTerms">预订条款</el-link>
          </div>
          <div class="flex gap-2">
            <el-button @click="showBookingDialog = false">取消</el-button>
            <el-button
              type="primary"
              @click="handleSubmit"
              :loading="submitting"
            >
              确认预订
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 预订条款弹窗 -->
    <el-dialog
      v-model="showTermsDialog"
      title="预订条款"
      width="500px"
      append-to-body
    >
      <div class="terms-content text-gray-600 dark:text-gray-400">
        <!-- 这里添加预订条款内容 -->
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  Star,
  Connection,
  Van,
  Trophy,
  Sunny,
  Food,
  OfficeBuilding,
  ArrowRight,
  QuestionFilled,
  Location,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { useUserStore } from "@/stores/user";
import service from "@/api/axios";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 加载状态
const loading = ref(false);

// 高德地图相关
const mapContainer = ref(null);
let map = null;
const mapKey = "ac63e78c8bfb172aac3c5be005a25f28"; // 高德地图Key
const securityJsCode = "bddeaa4d8587f8b446342a53ee0d4994"; // 高德地图安全密钥
const mapLoaded = ref(false);

// 设置高德地图安全密钥配置
if (typeof window !== 'undefined') {
  window._AMapSecurityConfig = {
    securityJsCode: securityJsCode
  };
}

// 测试酒店数据（当API请求失败时使用）
const testHotelData = {
  id: 1,
  name: "贵港大酒店",
  rating: 4.5,
  reviewCount: 1234,
  address: "贵港市港北区市中心广场1号",
  images: [
    "https://img0.baidu.com/it/u=3783317360,4121630497&fm=253&fmt=auto?w=608&h=456",
    "https://img0.baidu.com/it/u=1835438665,3879176067&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667",
    "https://img2.baidu.com/it/u=78329190,2130137121&fm=253&fmt=auto&app=138&f=JPEG?w=615&h=500",
  ],
  tags: ["四星级", "商务出行", "会议服务"],
  isFavorite: false,
  facilities: [
    { name: "免费WiFi", icon: "Connection" },
    { name: "停车场", icon: "Van" },
    { name: "健身房", icon: "Trophy" },
    { name: "游泳池", icon: "Sunny" },
    { name: "餐厅", icon: "Food" },
    { name: "会议室", icon: "OfficeBuilding" },
  ],
  introduction: `
    <div class="space-y-4">
      <p>贵港大酒店是一家集商务、休闲、餐饮、娱乐为一体的综合性酒店。酒店位于市中心，交通便利，环境优美。</p>
      <p>酒店拥有各类客房200余间，包括豪华套房、商务套房、标准间等。所有房间均配备高速网络、智能门锁、空调等现代化设施。</p>
      <p>酒店设有中餐厅、西餐厅、咖啡厅等多个餐饮场所，可为宾客提供各式美食。同时配备多个不同规模的会议室，可承接各类商务会议、培训、宴会等活动。</p>
      <p>休闲娱乐设施包括健身房、游泳池、SPA等，让宾客在繁忙之余享受优质的休闲时光。</p>
    </div>
  `,
  subway: "距离1号线市民广场站步行5分钟",
  landmarks: "近市民广场、市政府、贵港国际会展中心",
  rooms: [
    {
      id: 1,
      name: "豪华大床房",
      image:
        "https://img0.baidu.com/it/u=1314258708,1747191997&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500",
      description: "35平米 | 大床 | 2-3层 | 市景",
      price: 488,
      available: 5,
      features: ["免费WiFi", "免费停车", "24小时热水", "窗户"],
    },
    {
      id: 2,
      name: "行政套房",
      image:
        "https://img1.baidu.com/it/u=3397330351,3576136981&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500",
      description: "55平米 | 大床 | 15-20层 | 江景",
      price: 888,
      available: 2,
      features: ["免费WiFi", "免费停车", "行政礼遇", "观景阳台"],
    },
    {
      id: 3,
      name: "标准双床房",
      image:
        "https://img0.baidu.com/it/u=3988307251,2212851460&fm=253&fmt=auto&app=138&f=JPEG?w=667&h=500",
      description: "40平米 | 双床 | 5-8层 | 市景",
      price: 388,
      available: 8,
      features: ["免费WiFi", "免费停车", "24小时热水", "窗户"],
    },
  ],
  // 周边设施测试数据
  surroundings: [
    {
      category: "交通设施",
      facilities: [
        { name: "贵港汽车站", distance: "步行约10分钟 (800米)" },
        { name: "贵港火车站", distance: "驾车约15分钟 (5公里)" },
        { name: "贵港市民广场地铁站", distance: "步行约5分钟 (400米)" },
        { name: "机场快线", distance: "酒店门口" }
      ]
    },
    {
      category: "购物场所",
      facilities: [
        { name: "万达广场", distance: "步行约8分钟 (650米)" },
        { name: "华润万象城", distance: "步行约15分钟 (1.2公里)" },
        { name: "贵港百货大楼", distance: "步行约5分钟 (400米)" },
        { name: "永福购物中心", distance: "驾车约10分钟 (3公里)" }
      ]
    },
    {
      category: "餐饮美食",
      facilities: [
        { name: "老街口粉面", distance: "步行约3分钟 (200米)" },
        { name: "贵港烧鹅店", distance: "步行约6分钟 (500米)" },
        { name: "星巴克咖啡", distance: "酒店一层" },
        { name: "肯德基", distance: "步行约5分钟 (400米)" }
      ]
    },
    {
      category: "休闲娱乐",
      facilities: [
        { name: "贵港博物馆", distance: "驾车约8分钟 (2.5公里)" },
        { name: "贵港图书馆", distance: "步行约12分钟 (1公里)" },
        { name: "中央公园", distance: "步行约10分钟 (800米)" },
        { name: "环球影城", distance: "步行约7分钟 (600米)" }
      ]
    }
  ],
  // 用户点评测试数据
  reviews: [
    {
      id: 1,
      username: "张先生",
      avatar: "",
      date: "2023-06-15",
      rating: 5,
      content: "酒店地理位置优越，就在市中心，出行非常方便。房间宽敞明亮，设施齐全且新。服务人员态度很好，前台办理入住和退房都很高效。早餐品种丰富，味道不错。总体来说是一次很满意的住宿体验。",
      reply: "尊敬的张先生，感谢您对我们酒店的认可和评价。我们很高兴您对住宿体验感到满意，期待您的再次光临！"
    },
    {
      id: 2,
      username: "李女士",
      avatar: "",
      date: "2023-05-28",
      rating: 4.5,
      content: "房间干净整洁，床很舒服，睡眠质量好。酒店的服务态度不错，前台小姐姐很热情。唯一的不足是早餐的品种可以再丰富一些。总体来说性价比很高，下次来贵港还会选择这里。",
      reply: ""
    },
    {
      id: 3,
      username: "王经理",
      avatar: "",
      date: "2023-05-10",
      rating: 4,
      content: "商务出差入住，酒店的会议设施很完善，服务也很到位。房间隔音效果一般，走廊上有些吵。洗浴用品质量还不错，但是没有一次性拖鞋，需要自带或者找前台要。健身房器材种类很多，早餐品种丰富。",
      reply: "尊敬的王经理，感谢您的宝贵意见。关于隔音问题我们已经记录，将会加强改进。针对一次性拖鞋的问题，我们已经调整了流程，确保每个房间都配备齐全。期待您的再次光临！"
    },
    {
      id: 4,
      username: "刘游客",
      avatar: "",
      date: "2023-04-22",
      rating: 3.5,
      content: "酒店位置还不错，距离主要景点都比较近。房间设施有点旧了，空调声音有点大。卫生间干净但是淋浴水压不太稳定。服务态度一般，前台办理入住时有点慢。总体来说是中规中矩的体验。",
      reply: ""
    },
    {
      id: 5,
      username: "陈女士",
      avatar: "",
      date: "2023-03-18",
      rating: 5,
      content: "带孩子旅游入住的，酒店的工作人员非常热情，特别照顾了我们的需求。房间很大很干净，提供了婴儿床和额外的毛巾。酒店的游泳池很棒，孩子玩得很开心。早餐也很丰富，有适合孩子的食物。非常满意的一次住宿。",
      reply: "尊敬的陈女士，感谢您选择我们酒店。我们非常高兴能为您和孩子提供愉快的住宿体验。我们一直致力于为所有客人提供温馨的服务，特别是家庭客人。期待您和家人的再次光临！"
    }
  ]
};

// 评分分布测试数据
const ratingDistribution = ref([
  { label: '位置', percentage: 95, color: '#67c23a' },
  { label: '服务', percentage: 90, color: '#67c23a' },
  { label: '设施', percentage: 88, color: '#67c23a' },
  { label: '卫生', percentage: 92, color: '#67c23a' },
  { label: '舒适', percentage: 93, color: '#67c23a' },
  { label: '性价比', percentage: 85, color: '#67c23a' }
]);

// 酒店数据
const hotel = ref({...testHotelData});

// 选项卡
const activeTab = ref("intro");

// 日期选择
const dateRange = ref([]);

// 选中的房间
const selectedRoom = ref(null);

// 预订表单
const showBookingDialog = ref(false);
const bookingFormRef = ref(null);
const showTermsDialog = ref(false);
const submitting = ref(false);
const bookingForm = reactive({
  roomCount: 1,
  guestCount: 1,
  contactName: "",
  contactPhone: "",
  contactEmail: "",
  arrivalTime: "",
  remarks: "",
  guests: [{ name: "", idType: "idcard", idNumber: "" }],
});

// 表单验证规则
const bookingRules = {
  roomCount: [{ required: true, message: "请选择房间数量", trigger: "change" }],
  guestCount: [
    { required: true, message: "请选择入住人数", trigger: "change" },
  ],
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  contactEmail: [
    { required: true, message: "请输入电子邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  arrivalTime: [
    { required: true, message: "请选择预计到店时间", trigger: "change" },
  ],
};

// 方法
const handleDateChange = (val) => {
  if (!val || !val.length) {
    ElMessage.warning("请选择入住和离店日期");
    return;
  }
};

// 收藏/取消收藏
const toggleFavorite = async () => {
  if (!checkLogin()) return;
  
  try {
    if (hotel.value.isFavorite) {
      // 取消收藏
      await service.delete(`/user/favorites/${hotel.value.id}`);
      hotel.value.isFavorite = false;
      ElMessage.success("已取消收藏");
    } else {
      // 添加收藏
      await service.post("/user/favorites", { hotelId: hotel.value.id });
      hotel.value.isFavorite = true;
      ElMessage.success("收藏成功");
    }
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败，请重试");
  }
};

// 检查收藏状态
const checkFavoriteStatus = async (hotelId) => {
  if (!userStore.token) return;
  
  try {
    const response = await service.get(`/user/favorites/status`, {
      params: { hotelIds: hotelId }
    });
    
    if (response && Array.isArray(response)) {
      hotel.value.isFavorite = response.includes(parseInt(hotelId));
    }
  } catch (error) {
    console.error("获取收藏状态失败:", error);
  }
};

// 检查登录状态
const checkLogin = () => {
  if (!userStore.token) {
    ElMessageBox.confirm("登录后才能操作，是否前往登录？", "提示", {
        confirmButtonText: "去登录",
        cancelButtonText: "取消",
        type: "warning",
    })
      .then(() => {
      router.push({
        path: "/login",
        query: { redirect: router.currentRoute.value.fullPath },
      });
      })
      .catch(() => {});
      return false;
  }
  return true;
};

const handleBookRoom = async (room) => {
  if (!dateRange.value || !dateRange.value.length) {
    ElMessage.warning("请先选择入住和离店日期");
    return;
  }

  if (!checkLogin()) return;
  
  selectedRoom.value = room;
  showBookingDialog.value = true;
};

const formatDate = (date) => {
  return date ? dayjs(date).format("YYYY-MM-DD") : "";
};

const calculateRoomFee = () => {
  if (!selectedRoom.value || !dateRange.value || dateRange.value.length !== 2) {
    return 0;
  }
  const nights = Math.ceil(
    (dateRange.value[1] - dateRange.value[0]) / (1000 * 60 * 60 * 24),
  );
  return selectedRoom.value.price * bookingForm.roomCount * nights;
};

const calculateServiceFee = () => {
  return Math.floor(calculateRoomFee() * 0.1);
};

const calculateTotalFee = () => {
  return calculateRoomFee() + calculateServiceFee();
};

const calculateNights = () => {
  if (!dateRange.value || dateRange.value.length !== 2) return 0;
  return Math.ceil(
    (dateRange.value[1] - dateRange.value[0]) / (1000 * 60 * 60 * 24),
  );
};

const handleRoomCountChange = (value) => {
  // 更新入住人表单数组
  const currentGuests = bookingForm.guests.length;
  if (value > currentGuests) {
    for (let i = currentGuests; i < value; i++) {
      bookingForm.guests.push({ name: "", idType: "idcard", idNumber: "" });
    }
  } else if (value < currentGuests) {
    bookingForm.guests.splice(value);
  }
  // 确保入住人数不超过房间容量
  if (bookingForm.guestCount > value * 2) {
    bookingForm.guestCount = value * 2;
  }
};

const showTerms = () => {
  showTermsDialog.value = true;
};

const handleSubmit = async () => {
  if (!bookingFormRef.value) return;

  try {
    await bookingFormRef.value.validate();

    // 构建订单数据
    const orderData = {
      type: "hotel",
      hotelId: hotel.value.id,
      hotelName: hotel.value.name,
      roomId: selectedRoom.value.id,
      roomName: selectedRoom.value.name,
      roomImage: selectedRoom.value.image,
      checkIn: dateRange.value[0],
      checkOut: dateRange.value[1],
      guests: bookingForm.guests,
      price: selectedRoom.value.price,
      description: selectedRoom.value.description,
      address: hotel.value.address,
      nights: calculateNights(),
      roomCount: bookingForm.roomCount || 1,
      totalAmount:
        selectedRoom.value.price *
        calculateNights() *
        (bookingForm.roomCount || 1),
    };

    // 跳转到确认订单页面
    router.push({
      path: "/order/confirm",
      query: {
        type: "hotel",
        data: encodeURIComponent(JSON.stringify(orderData)),
      },
    });
  } catch (error) {
    console.error("表单验证失败:", error);
    ElMessage.error("预订失败，请重试");
  }
};

// 获取酒店详情
const fetchHotelDetail = async () => {
    const hotelId = route.params.id;
  if (!hotelId) {
    ElMessage.error("酒店ID无效");
    router.push("/hotel");
    return;
  }

  loading.value = true;
  try {
    // 调用获取酒店详情API
    const response = await service.get(`/public/hotels/${hotelId}`);
    
    if (response && response.data && response.code === 200) {
      // 保存API返回的数据
      const apiData = response.data;
      
      // 使用API数据，但如果surroundings或reviews为空，使用测试数据的相应部分
      hotel.value = {
        ...apiData,
        surroundings: apiData.surroundings && apiData.surroundings.length > 0 
                    ? apiData.surroundings 
                    : testHotelData.surroundings,
        reviews: apiData.reviews && apiData.reviews.length > 0 
               ? apiData.reviews 
               : testHotelData.reviews
      };
      
      // 如果用户已登录，检查是否已收藏
      if (userStore.token) {
        await checkFavoriteStatus(hotelId);
      } else {
        // 未登录用户默认未收藏
        hotel.value.isFavorite = false;
      }
    } else {
      // 使用测试数据
      hotel.value = {...testHotelData};
    }
      
    // 如果地图已加载，更新地图上的酒店位置
    if (mapLoaded.value && hotel.value.address) {
      searchHotelLocation(hotel.value.name, hotel.value.address);
    }
  } catch (error) {
    console.error("获取酒店详情失败:", error);
    // 使用测试数据
    hotel.value = {...testHotelData};
  } finally {
    loading.value = false;
  }
};

// 获取可用房间
const fetchAvailableRooms = async () => {
  if (!dateRange.value || dateRange.value.length !== 2) return;
  
  const hotelId = route.params.id;
  const params = {
    checkIn: formatDate(dateRange.value[0]),
    checkOut: formatDate(dateRange.value[1])
  };
  
  try {
    const response = await service.get(`/public/hotels/${hotelId}/rooms`, { params });
    
    if (response && response.code === 200 && response.data) {
      hotel.value.rooms = response.data;
    }
  } catch (error) {
    console.error("获取可用房间失败:", error);
    // 保持测试数据的房间信息
  }
};

// 监听日期变化获取可用房间
const watchDateRange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    fetchAvailableRooms();
  }
};

// 加载高德地图脚本
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 如果AMap已存在且可用，直接返回
    if (window.AMap && typeof window.AMap.Map === 'function') {
      resolve(window.AMap);
      return;
    }
    
    // 清除之前可能存在的脚本，防止冲突
    const existingScript = document.querySelector('script[src*="webapi.amap.com"]');
    if (existingScript) {
      existingScript.parentNode.removeChild(existingScript);
    }
    
    // 重置 AMap 对象，防止使用旧的实例
    if (window.AMap) {
      window.AMap = undefined;
    }
    
    // 确保安全配置已设置
    if (typeof window !== 'undefined' && !window._AMapSecurityConfig) {
      window._AMapSecurityConfig = {
        securityJsCode: securityJsCode
      };
    }
    
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    
    // 创建并加载脚本
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${mapKey}&plugin=AMap.PlaceSearch&t=${timestamp}`;
    
    script.onload = () => {
      resolve(window.AMap);
    };
    
    script.onerror = (error) => {
      reject(new Error('地图加载失败'));
    };
    
    document.head.appendChild(script);
  });
};

// 初始化地图
const initMap = async () => {
  try {
    // 确保地图容器存在
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      setTimeout(() => {
        initMap();
      }, 500);
      return;
    }

    // 确保地图尚未初始化
    if (map) return;

    // 加载高德地图脚本
    await loadAMapScript();

    // 再次确认DOM已经准备好
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      setTimeout(() => {
        initMap();
      }, 300);
      return;
    }

    // 创建地图实例，默认显示贵港市全貌
    map = new AMap.Map(mapContainer.value, {
      zoom: 14,
      center: [109.613196, 23.103333], // 贵港市中心坐标
      resizeEnable: true,
    });

    // 添加标记
    if (hotel.value.address) {
      searchHotelLocation(hotel.value.name, hotel.value.address);
    }
    
    mapLoaded.value = true;
  } catch (error) {
    console.error("地图初始化失败:", error);
  }
};

// 搜索酒店位置并添加标记
const searchHotelLocation = (hotelName, address) => {
  if (!map || !window.AMap) return;
  
  // 创建地点搜索实例
  const placeSearch = new AMap.PlaceSearch({
    pageSize: 1,
    pageIndex: 1,
    city: '贵港', // 限定城市
    citylimit: true,
  });

  // 优先使用完整地址搜索
  placeSearch.search(address, (status, result) => {
    if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
      // 获取第一个搜索结果的位置
      const position = [
        result.poiList.pois[0].location.lng,
        result.poiList.pois[0].location.lat
      ];
      
      // 添加标记
      addHotelMarker(position, hotelName);
    } else {
      // 如果地址搜索失败，尝试使用酒店名称搜索
      placeSearch.search(hotelName, (status, result) => {
        if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
          const position = [
            result.poiList.pois[0].location.lng,
            result.poiList.pois[0].location.lat
          ];
          
          addHotelMarker(position, hotelName);
        } else {
          console.warn("未找到酒店位置");
        }
      });
    }
  });
};

// 添加酒店标记
const addHotelMarker = (position, name) => {
  if (!map) return;
  
  // 清除之前的标记
  map.clearMap();
  
  // 创建标记
  const marker = new AMap.Marker({
    position: position,
    title: name,
    map: map,
    icon: new AMap.Icon({
      size: new AMap.Size(40, 40),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
      imageSize: new AMap.Size(40, 40)
    }),
    offset: new AMap.Pixel(-20, -40)
  });
  
  // 设置地图中心和缩放级别
  map.setCenter(position);
  map.setZoom(15);
  
  // 创建信息窗体
  const infoWindow = new AMap.InfoWindow({
    content: `
      <div style="padding:10px;">
        <h3 style="font-weight:bold;margin-bottom:5px;">${name}</h3>
        <p style="font-size:12px;color:#666;">${hotel.value.address}</p>
      </div>
    `,
    offset: new AMap.Pixel(0, -30)
  });
  
  // 点击标记时显示信息窗口
  marker.on('click', () => {
    infoWindow.open(map, marker.getPosition());
  });
  
  // 自动打开信息窗口
  infoWindow.open(map, marker.getPosition());
};

// 清理地图资源
const cleanupMap = () => {
  try {
    // 销毁地图实例
    if (map) {
      map.clearMap();
      map.destroy();
      map = null;
    }
    
    mapLoaded.value = false;
  } catch (error) {
    console.warn("清理地图资源时发生错误:", error);
  }
};

onMounted(async () => {
  fetchHotelDetail();
  
  // 监听日期变化
  watch(dateRange, watchDateRange);
  
  // 监听登录状态变化
  watch(() => userStore.token, async (newVal) => {
    if (newVal) {
      await checkFavoriteStatus(route.params.id);
    } else {
      hotel.value.isFavorite = false;
    }
  });

  // 确保安全配置已设置
  if (typeof window !== 'undefined') {
    window._AMapSecurityConfig = {
      securityJsCode: securityJsCode
    };
  }
  
  // 确保DOM已更新
  await nextTick();
  
  // 延迟初始化，确保DOM完全渲染
  setTimeout(() => {
    initMap();
  }, 800);
});

onBeforeUnmount(() => {
  cleanupMap();
});
</script>

<style lang="scss" scoped>
.hotel-detail {
  .rich-text {
    @apply text-gray-600 dark:text-gray-400;

    p {
      @apply mb-4 last:mb-0;
    }
  }

  :deep(.el-carousel__item) {
    border-radius: 8px;
    overflow: hidden;
  }

  :deep(.el-tabs__nav-wrap::after) {
    @apply dark:bg-gray-700;
  }

  :deep(.el-tabs__item) {
    @apply text-gray-600 dark:text-gray-400;

    &.is-active {
      @apply text-primary-600 dark:text-primary-400;
    }

    &:hover {
      @apply text-primary-500 dark:text-primary-300;
    }
  }

  .room-card {
    @apply transition-all duration-300;

    &:hover {
      @apply shadow-md dark:shadow-gray-800/50;
    }
  }

  :deep(.el-dialog) {
    @apply dark:bg-gray-800;

    .el-dialog__header {
      @apply dark:text-white dark:border-gray-700;
    }

    .el-dialog__body {
      @apply dark:text-gray-300;
    }
  }

  :deep(.el-form-item__label) {
    @apply dark:text-gray-400;
  }

  :deep(.el-input__wrapper) {
    @apply dark:bg-gray-700 dark:border-gray-600;
  }

  :deep(.el-input__inner) {
    @apply dark:text-gray-300;

    &::placeholder {
      @apply dark:text-gray-500;
    }
  }

  :deep(.el-textarea__inner) {
    @apply dark:bg-gray-700 dark:border-gray-600 dark:text-gray-300;

    &::placeholder {
      @apply dark:text-gray-500;
    }
  }
}

.booking-dialog {
  :deep(.el-dialog) {
    @apply max-h-[90vh] flex flex-col;
    margin-top: 5vh !important;

    .el-dialog__header {
      @apply p-4 border-b border-gray-100 dark:border-gray-700;
      margin-right: 0;
    }

    .el-dialog__body {
      @apply p-0 flex-1 overflow-hidden;
    }

    .el-dialog__footer {
      @apply p-4 border-t border-gray-100 dark:border-gray-700;
      margin-top: 0;
    }
  }

  .dialog-content {
    @apply h-full flex flex-col;
    max-height: calc(90vh - 120px); // 减去头部和底部的高度
  }

  .form-content {
    @apply flex-1 overflow-y-auto px-6 py-4;

    &::-webkit-scrollbar {
      @apply w-2;
    }

    &::-webkit-scrollbar-track {
      @apply bg-gray-100 dark:bg-gray-700 rounded-full;
    }

    &::-webkit-scrollbar-thumb {
      @apply bg-gray-300 dark:bg-gray-600 rounded-full;

      &:hover {
        @apply bg-gray-400 dark:bg-gray-500;
      }
    }
  }

  .form-section {
    @apply border-b border-gray-100 dark:border-gray-700 pb-6;

    &:last-child {
      @apply border-b-0 pb-0;
    }
  }

  .room-preview {
    @apply transition-all duration-300 shadow-sm;
  }

  .booking-notice {
    ul {
      @apply dark:text-gray-400;
    }
  }
}
</style>
